#include "Game.h"
#include <algorithm>

static bool isGoal(const Level& lvl, const Vec2i& p) {
    for (auto& g : lvl.goals()) if (g==p) return true;
    return false;
}

Game::Game(const Level& level) : lvl(level) {
    st.player = lvl.playerStart();
    st.boxes = lvl.boxes();
    undoStack.clear();
    steps = 0;
}

bool Game::move(Direction dir) {
    undoStack.push(st);
    bool ok = MoveSystem::move(lvl, st, dir);
    if (!ok) { undoStack.pop(); return false; }
    steps++;
    return true;
}

void Game::reset() {
    st.player = lvl.playerStart();
    st.boxes = lvl.boxes();
    undoStack.clear();
    steps = 0;
}

bool Game::undo() {
    if (!undoStack.canUndo()) return false;
    st = undoStack.pop();
    if (steps>0) steps--;
    return true;
}

bool Game::completed() const {
    for (auto& g : lvl.goals()) {
        bool ok=false;
        for (auto& b : st.boxes) if (b==g) { ok=true; break; }
        if (!ok) return false;
    }
    return true;
}

int Game::stepCount() const { return steps; }
const GameState& Game::state() const { return st; }
const Level& Game::level() const { return lvl; }